package ma.belsoft.syga.webapp.action;

import java.util.List;

import ma.belsoft.syga.model.Annonce;
import ma.belsoft.syga.service.AnnonceManager;

import com.opensymphony.xwork2.Preparable;

public class AnnonceAction extends BaseAction implements Preparable {
    private AnnonceManager annonceManager;
    private List annonces;
    private Annonce annonce;
    private Long id;
    private String query;

	public void setAnnonceManager(AnnonceManager annonceManager) {
		this.annonceManager = annonceManager;
	}

	public List getAnnonces() {
        return annonces;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String annonceId = getRequest().getParameter("annonce.id");
            if (annonceId != null && !annonceId.equals("")) {
                annonce = annonceManager.get(new Long(annonceId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        annonces = annonceManager.search(query, Annonce.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Annonce getAnnonce() {
        return annonce;
    }

    public void setAnnonce(Annonce annonce) {
        this.annonce = annonce;
    }

    public String delete() {
        annonceManager.remove(annonce.getId());
        saveMessage(getText("annonce.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            annonce = annonceManager.get(id);
        } else {
            annonce = new Annonce();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (annonce.getId() == null);

        annonceManager.save(annonce);

        String key = (isNew) ? "annonce.added" : "annonce.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}